package org.example.redis.demo;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class HashRedisDemo {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //存放
    public void a(){
        HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
        ops.put("A","a","aa");
        ops.put("A","b","bb");
        ops.put("A","c","cc");
        ops.putIfAbsent("A","a","aa2");
        ops.putIfAbsent("A","d","dd2");
        ops.put("A","h","14");
        HashMap map = new HashMap();
        map.put("e","ee");
        map.put("f","ff");
        map.put("g","gg");
        map.put("A",map);
    }
    //获取
    public void b(){
        HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
        Object a = ops.get("A", "a");
        Object k = ops.get("A", "k");
        //全部获取
        Map<Object, Object> map = ops.entries("A");
        //获取指定键集和值集
        Set<Object> keys = ops.keys("A");
        List<Object> values = ops.values("A");
        //获得随机的键集
        Object randomKey = ops.randomKey("A");
        List<Object> randomKeys = ops.randomKeys("A",3);
        log.info("a:{},k:{}",a,k);
        log.info("map:{}",map);
        log.info("keys:{},values:{}",keys,values);
        log.info("r:{},rs:{}",randomKey,randomKeys);
    }
    //其他
    public void c(){
        HashOperations<String, Object, Object> ops = stringRedisTemplate.opsForHash();
        Long size = ops.size("A");
        Boolean hasKey1 = ops.hasKey("A", "a");
        Boolean hasKey2 = ops.hasKey("A", "k");
        ops.delete("A", "a","b");
        ops.increment("A", "h",1);
        ops.increment("A", "h",1.5);
        log.info("size:{},hasKey1:{},hasKey2:{}",size,hasKey1,hasKey2);
    }
}
